package com.open.capacity.finance.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.open.capacity.finance.config.Globals;
import com.open.capacity.finance.dao.AuditAnalysisDao;
import com.open.capacity.finance.dao.SourceBaseAssetDao;
import com.open.capacity.finance.dao.SourcePzDao;
import com.open.capacity.finance.dto.AuditModelBaseResult;
import com.open.capacity.finance.dto.audit_model_27.AuditModelResult;
import com.open.capacity.finance.dto.audit_model_27.AuditModelStep1;
import com.open.capacity.finance.dto.audit_model_27.AuditModelStep2;
import com.open.capacity.finance.dto.audit_model_27.ExcelData;
import com.open.capacity.finance.entity.AuditModel;
import com.open.capacity.finance.entity.AuditModelRule;
import com.open.capacity.finance.entity.SourceBaseBudgetExcute;
import com.open.capacity.finance.service.AbstractAuditMakeResultFactory;
import com.open.capacity.finance.service.AuditModelRuleService;
import com.open.capacity.finance.service.AuditModelService;
import com.open.capacity.finance.service.SourceBaseUsecarService;
import com.open.capacity.finance.util.FileUtil;
import com.open.capacity.utils.BigDecimalUtil;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.encrypt.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AuditModelActuator27ServiceImpl<T extends AuditModelBaseResult> extends AbstractAuditMakeResultFactory {

    @Autowired
    private AuditAnalysisDao analysisDao;

    @Autowired
    private AuditModelRuleService ruleService;

    @Autowired
    private AuditModelService modelService;

    @Autowired
    private SourceBaseUsecarService usecarService;

    @Autowired
    private SourceBaseAssetDao assetDao;

    @Autowired
    private SourcePzDao pzDao;


    @Override
    protected T analyseResultData(String modelId, Map param) {
        String companyId = param.containsKey("companyId") ? param.get("companyId").toString() : "";
        param.put("ztId", "101");
        Integer kjnd = Integer.parseInt(param.get("kjnd").toString());
        AuditModelResult result = new AuditModelResult();
        AuditModel model = modelService.findById(modelId);
        Assert.notNull(model, "找不到该模型");
        List<AuditModelRule> rules = ruleService.findByModelId(modelId);

        rules.forEach(t -> {
            param.put(t.getConfKey(), t.getConfValue());
        });
        result.setModelName(model.getCodeAndName());
        if (!param.containsKey("flag")) { //默认查异常数据
            param.put("flag", 1);
        }

        List<AuditModelStep2> pzList = pzDao.getMonthData(param);
        param.remove("kjnd");
        List<AuditModelStep2> step2List = assetDao.getMonthData(param);


        //并集
        for (AuditModelStep2 item : pzList) {
            Optional<AuditModelStep2> first = step2List.stream().filter(t -> t.getCompanyId().equals(item.getCompanyId()) && t.getKjnd() != null && t.getKjnd().equals(item.getKjnd()) && t.getMonth() != null && t.getMonth().equals(item.getMonth())).findFirst();
            if (!first.isPresent()) {
                item.setAssetMoney(BigDecimal.ZERO);
                item.setCompanyName(Globals.companyList.stream().filter(t -> t.getId().equals(item.getCompanyId())).findFirst().get().getFullName());
                step2List.add(item);
            }
        }

        for (AuditModelStep2 item : step2List) {
            Optional<AuditModelStep2> first = pzList.stream().filter(t -> t.getCompanyId().equals(item.getCompanyId()) && t.getKjnd().equals(item.getKjnd()) && t.getMonth().equals(item.getMonth())).findFirst();
            if (first.isPresent()) {
                item.setFinanceMoney(first.get().getD());
            }

            if (item.getFinanceMoney() != null && item.getAssetMoney().compareTo(item.getFinanceMoney()) == 0) {
                item.setMatch(true);
                item.setFlag(0);
            } else {
                item.setMatch(false);
                item.setFlag(1);
            }
        }


        List<AuditModelStep1> step1List = new ArrayList<>();
        TreeMap<String, List<AuditModelStep2>> collect = step2List.stream().filter(t -> t.getKjnd() != null && t.getKjnd().equals(kjnd)).collect(Collectors.groupingBy(item ->
                item.getCompanyId() + "_" + item.getCompanyName() + "_" + item.getAssetType() + "_" + item.getKjnd(), TreeMap::new, Collectors.toList()));

        for (Map.Entry<String, List<AuditModelStep2>> entry_item : collect.entrySet()) {
            AuditModelStep1 item = new AuditModelStep1();
            String key = entry_item.getKey().toString();
            String _companyId = key.split("_")[0];
            String companyName = key.split("_")[1];
            String assetType = key.split("_")[2];

            item.setCompanyId(_companyId);
            item.setCompanyName(companyName);
            item.setKjnd(kjnd);
            item.setAssetType(assetType);


            BigDecimal financeQc = BigDecimal.ZERO;
            BigDecimal financeYe = BigDecimal.ZERO;
            Optional<AuditModelStep2> first2 = pzList.stream().filter(t -> t.getCompanyId().equals(_companyId) && t.getKjnd().equals(kjnd) && t.getMonth().equals(0)).findFirst();
            if (first2.isPresent()) {
                financeQc = financeQc.add((first2.get().getFinanceYe()));
            }
            for (AuditModelStep2 s : entry_item.getValue()) {
                Optional<AuditModelStep2> first = pzList.stream().filter(t -> t.getCompanyId().equals(s.getCompanyId()) && t.getKjnd().equals(s.getKjnd()) && t.getMonth().equals(s.getMonth())).findFirst();
                if (first.isPresent()) {
                    financeYe = financeYe.add((first.get().getFinanceYe()));
                }
            }
            BigDecimal assetMoney = BigDecimal.ZERO;
            assetMoney = step2List.stream().filter(b -> b.getCompanyId().equals(_companyId) && b.getKjnd() != null && b.getKjnd() <= kjnd)
                    .map(AuditModelStep2::getAssetMoney)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            item.setAssetMoney(assetMoney);
            item.setFinanceQc(financeQc);
            item.setFinanceYe(financeYe);
            if (item.getAssetMoney().compareTo(item.getFinanceYe()) == 0) {
                item.setMatch(true);
                item.setFlag(0);
            } else {
                item.setMatch(false);
                item.setFlag(1);
            }

            step1List.add(item);
        }
        step2List = step2List.stream().filter(t -> t.getKjnd() != null && t.getKjnd().equals(kjnd)).collect(Collectors.toList());

        step1List.sort(Comparator.comparing(AuditModelStep1::getCompanyId)
                .thenComparing(AuditModelStep1::getKjnd));
        step2List.sort(Comparator.comparing(AuditModelStep2::getCompanyId)
                .thenComparing(AuditModelStep2::getKjnd, Comparator.nullsLast(Integer::compareTo))
                .thenComparing(AuditModelStep2::getMonth));

        //只显示异常
        Integer flag = param.containsKey("flag") && StringUtil.isNotEmpty(param.get("flag").toString()) ? Integer.parseInt(param.get("flag").toString()) : 0;
        if (flag.equals(1)) {
            step2List = step2List.stream().filter(t -> t.getFlag() != null && t.getFlag().equals(1)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(step2List)) {
                step1List = step1List.stream().filter(t -> t.getFlag() != null && t.getFlag().equals(1)).collect(Collectors.toList());
            }
        }
        step2List = step2List.stream().filter(t -> t.getMonth() > 0).collect(Collectors.toList());
        result.setCompanyId(companyId);
        result.setStep1List(step1List);
        result.setStep2List(step2List);
        if (CollectionUtils.isEmpty(step2List)) {
            result.setExists(0);
        } else {
            result.setExists(1);

            //持久化本地
            persistence(result);
        }

        return (T) result;
    }

    @Override
    protected int persistence(AuditModelBaseResult data) {
        int result = 0;

        String content = JSON.toJSONString(data, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);

        data.setResultFileMd5(Md5Utils.hash(content));
        data.setResultFileUrl("/upload/analyse/model27_" + data.getCompanyId() + "_" + data.getResultFileMd5() + ".json");

        Writer write = null;
        try {
            File file = new File(fileuploadPath + "/upload/analyse/model27_" + data.getCompanyId() + "_" + data.getResultFileMd5() + ".json");
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            // 写入文件
            write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            write.write(content);
            write.flush();
            write.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                write.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return result;
    }

    @Override
    public T getData(String modelId, Map param) {
        return analyseResultData(modelId, param);
    }


    /**
     * 从本地加载数据
     */
    public AuditModelBaseResult getDataFromJson(String jsonUrl, Map param) {
        AuditModelResult result = null;
        try {
            String json = FileUtil.readTxtToJson(fileuploadPath + jsonUrl);
            result = JSONObject.parseObject(json, new TypeReference<AuditModelResult>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        filterCondition(result, param);

        return result;
    }

    /**
     * 本地json数据条件过滤
     */
    private AuditModelResult filterCondition(AuditModelResult orig, Map param) {
        AuditModelResult result = orig;
        String companyId = MapUtils.getString(param, "companyId");
        Integer kjnd = MapUtils.getInteger(param, "kjnd");
        Integer flag = MapUtils.getInteger(param, "flag");

        List<AuditModelStep1> list1 = orig.getStep1List();
        List<AuditModelStep2> list2 = orig.getStep2List();

        if (StringUtil.isNotEmpty(companyId)) {
            list1 = list1.stream().filter(t -> t.getCompanyId().equals(companyId)).collect(Collectors.toList());
            list2 = list2.stream().filter(t -> t.getCompanyId().equals(companyId)).collect(Collectors.toList());
        }
        if (kjnd != null) {
            list1 = list1.stream().filter(t -> t.getKjnd().equals(kjnd)).collect(Collectors.toList());
            list2 = list2.stream().filter(t -> t.getKjnd().equals(kjnd)).collect(Collectors.toList());
        }
        if (flag != null) {
            list1 = list1.stream().filter(t -> t.getFlag().equals(flag)).collect(Collectors.toList());
            list2 = list2.stream().filter(t -> t.getFlag().equals(flag)).collect(Collectors.toList());
        }

        result.setStep1List(list1);
        result.setStep2List(list2);

        return result;
    }

    public void exportExcel(String modelId, Map params, HttpServletResponse response) {
        AuditModelResult t = (AuditModelResult) analyseResultData(modelId, params);

        export(t, response);
    }

    @Override
    public void exportExcelFromJson(String modelId, String jsonUrl, HttpServletResponse response) {
        AuditModelResult t = null;
        try {
            String json = FileUtil.readTxtToJson(fileuploadPath + jsonUrl);
            t = JSONObject.parseObject(json, new TypeReference<AuditModelResult>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        export(t, response);
    }

    private void export(AuditModelResult t, HttpServletResponse response) {
        List<ExcelData> result = t.getStep1List().stream().map(item -> {
            ExcelData model = new ExcelData();
            BeanUtils.copyProperties(item, model);
            return model;
        }).collect(Collectors.toList());

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=download_27.xls");
        OutputStream ouputStream = null;
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(),
                ExcelData.class, result);
        try {
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
        } catch (Exception e) {
            throw new RuntimeException("系统异常");
        } finally {
            try {
                if (ouputStream != null) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("系统异常");
            }
        }
    }
}
